<?php
namespace Seller\Controller;
use Think\AjaxPage;
use Think\Controller;

class OrderController extends CommonController {

    public function _initialize() {
        $params = array("ajax_logs_list","msg_conf","edit_config","cancel","detail","set_status","del","edit",
           "selectexcel","modify_price","invoice","return_good_info","scoket" );
        parent::_initialize($params);
    }

    //订单列表
    public function index() {
        //当执行查询的时候
        $search = I('get.btn');
        $export =  I('get.export');

        //查询自己店铺的订单
        $map['shop_id'] = session("shop_id");
        if ($search || $export) {
            $start = strtotime(trim(I('get.start_time')));
            $end = strtotime(trim(I('get.end_time')));

            //填写下单时间
            if ($start && $end) {
                $map['time'] = array('between', array($start, $end));
            } elseif($start) {
                $map['time'] = array('EGT', $start);
            } elseif($end) {
                $map['time'] = array('ELT', $end);
            }

            //选择订单状态
            $status = I('get.status');
            if ($status != -2) {
                if ($status == -1) {
                    $map['status']  = array('not in','-1,3');
                } elseif ($status == -3) {
                    $map['status'] = -1;
                } else {
                    $map['status'] = $status;
                }
                $this->assign('x_status', $status);
            }

            //下单用户名或手机号码
            $u_name = trim(I('get.user_name'));
            if ($u_name) {

                $bool = preg_match("/^1[34578]{1}\d{9}$/",$u_name);
                if($bool){
                    $map['phone'] = $u_name;
                }else{
                    $map['consignee'] = array('like','%'.$u_name.'%');
                }
                $this->assign('u_name', $u_name);
            }

            //下单人用户名
            $user_phone = trim(I('get.user_phone'));
            if ($user_phone) {
                $where['agent_name'] = array('like','%'.$user_phone.'%');
                $agent_id = M('agent')->field('agent_id')->where($where)->select();
                $agent_ids ='';
                foreach ($agent_id as $v) {
                    $agent_ids .= $v['agent_id'].',';
                }

                $agent_ids = substr($agent_ids,0,strlen($agent_ids)-1);
                $map['uid'] = array('in', $agent_ids);
                $this->assign('u_phone', $user_phone);
            }

            //选择付款状态
            $is_pay = I('get.is_pay');
            if ($is_pay != -2) {
                $map['is_pay'] = $is_pay;
                $this->assign('x_pay', $is_pay);
            }

            //发货状态
            $is_deliver = I('get.is_deliver');
            if ($is_deliver != -2) {
                if ($is_deliver == 2) {
                    $map['is_platform'] = 1;//待平台发货
                    $map['is_deliver'] = -1;
                } else {
                    $map['is_deliver'] = $is_deliver;
                }
                $this->assign('x_deliver', $is_deliver);
            }

            //订单编号
            $order_id = I('get.order_id');
            if ($order_id) {
                $map['order_id'] = $order_id;
                $this->assign('orderId', $order_id);
            }
        }

        //查询分页
        $total = D('Order')->relation(true)->where($map)->count();
        $page = set_page($total, C('PAGE_NUM'));

        foreach($map as $key=>$val) {
            $page->parameter[$key] = urlencode($val);
        }
        $show = $page->show();
        $order = D('Order')->order('id DESC')->relation(true)->where($map)->select();

        //当执行导出数据的时候
        if ($export) {
            //把商品信息链接
            foreach ($order as $k=>$v) {
                $order[$k]['goods'] = M('orderGood')
                    ->alias('a')->join('LEFT JOIN __GOOD__ b ON a.good_id=b.id')
                    ->where( array('a.order_id'=>$v['id']) )
                    ->select();
            }
            $order = D('order')->format($order);
            $strTable ='<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;font-weight: bold;">订单编号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;"width="100">下单人</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">收货人</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">收货人号码</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">支付状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">订单状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">发货状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">下单时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">运费</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">收货地址</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">商品名称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">商品数量</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">单价</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">小计</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">订单总价(含运费)</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">商品货号</td>';
            $strTable .= '</tr>';
            foreach ($order as $key=>$val) {
                $address = $val['province'].$val['city'].$val['area'].$val['detail_address'];
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_id'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agent_name'].' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['is_pay'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['status'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['is_deliver'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['time'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['freight_price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$address.'</td>';
                $g_names = $good_sns = $num_s = $good_price = $avg = '';
                foreach($order[$key]['goods'] as $goods) {
                    $g_names .= $goods['g_name']."<br />";
                    $good_sns .= $goods['good_sn']."<br />";
                    $num_s .= $goods['num']."<br />";
                    $good_price .= $goods['goods_price']."<br />";
                    $avg .= ($goods['goods_price']/$goods['num'])."<br />";
                }
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$g_names.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$num_s.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$avg.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$good_price.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$good_sns.' </td>';
                $strTable .= '</tr>';
            }
            $strTable .='</table>';
            createExcel($strTable, '微商系统订单');
        } else {
            $order = D('Order')->order('id DESC')->relation(true)->where($map)->limit($page->firstRow.','.$page->listRows)->select();
        }
        //订单状态
        $order_status = array('-1' => '进行中', '3' => '交易成功', '-3'=>'已取消');
        //付款状态
        $pay_status = array('-1' => '未付款', '1' => '已付款');
        //发货状态
        $deliver_status = array('-1' => '未发货', '1' => '已发货', '2'=>'待平台发货');
        $this->assign('start_time',I('get.start_time'));
        $this->assign('end_time',I('get.end_time'));
        $this->assign('deliver_status', $deliver_status);
        $this->assign('pay_status', $pay_status);
        $this->assign('order_status', $order_status);
        $this->assign('page',$show);
        $this->assign('orders', $order);
        $this->display();
    }

    //取消订单
    public function cancel()
    {
        $oid = I('post.id');
        $order = M('order')->where( array('id'=> $oid) )->find();
        if($order){
            $tbl = C("DB_PREFIX")."agent";
            //修改订单状态
            M('order')->where( array('id'=>I('post.id')) )->save( array('status' => -1 ,'is_pay' => -1) );

            //还原库存
            $order_good = M("order_good")->where(array("order_id"=>$oid))->select();
            foreach($order_good as $key =>$value){
                //当商品为件的时候
                if($value['good_type'] == 2){
                    //先查出一箱是多少件
                    $per_num =  M("good")->where(array("id"=>$value["good_id"]))->getField("per_num");
                    M("good")->where(array("id"=>$value["good_id"]))->setInc("stock",$value['num']*$per_num);
                }else{
                    M("good")->where(array("id"=>$value["good_id"]))->setInc('stock',$value['num']);
                }
            }

            //把订单的金额返回预存款
            if($order['is_pay'] == 1) {
                $through = M('order_through')->where( array('order_id' => $oid , 'state'=>1) )->select();
                //更新上级代理的余额
                foreach ($through as $value) {
                    $amt = $value['price'] + $order['freight_price'];
                    M()->execute("UPDATE $tbl SET `money` = `money` + $amt WHERE agent_id = ".$value['uid']);

                    $content = GetAgentNameById($order['uid']).
                        " 取消订单：". $order['order_id'] ." 用户 ".GetAgentNameById($value['uid']) ." 退回金额：$amt 元";
                    wlm_write_log($value['uid'] ,$content ,$amt ,1);
                }
                //更新下单人的余额
                M()->execute("UPDATE $tbl SET `money` = `money` + ".$order['price']." WHERE agent_id = ".$order['uid']);
                $content = GetAgentNameById($order['uid']).
                    " 取消订单：". $order['order_id']." 退回金额：".$order['price'] ." 元";
                wlm_write_log($order['uid'] ,$content ,$order['price'] ,1);
            }
            $msg = GetManagerNameById(session("manager_id")). " 取消订单：". $order['order_id'];
            order_opt_log($msg ,$order['order_id']);
            $bool = 1;
        }else{
            $bool = -1;
        }
        $this->ajaxReturn($bool);
    }

    //订单详情
    public function detail() {
        //订单的基本信息和收货信息
        $map['id'] = I('get.id');
        $order = D('Order')->order('id DESC')->relation(true)->where($map)->find();
        //当订单完成并且是代理商品的时候，计算返利
        if($order['status'] == 3 && $order['is_platform'] == 0) {
            $rebate = M('rebate')->alias('a')
                ->join('LEFT JOIN __AGENT__ b ON a.re_agent=b.agent_id')
                ->where( array('order_id'=>$order['id']) )
                ->order('rebate_id ASC')
                ->select();
            $this->assign('rebate_num', count($rebate));
            $this->assign('rebate', $rebate);
        }
        //订单里面的商品
        $orderGood = M('orderGood')->alias('a')->join('LEFT JOIN __GOOD__ ON a.good_id=__GOOD__.id')->where( array('a.order_id'=>I('get.id')) )->select();
        //订单流向
        $id = I('get.id');
        $orderThrough = D('OrderThrough')->relation(true)->where( array('order_id'=>$id) )->order('id ASC')->select();
        //计算订单的总价格
        $sum = 0;
        foreach ($orderGood as $v) {
            $sum += $v['num'] * $v['price'];
        }
        if ($order['discount'] != 0) {
            $endSum = $sum - $order['discount'];
        }
        $pay_type = M("payment")->where("p_id = %d" ,array($order["pay_type"]))->getField("p_name");
        //获取操作纪录
        $order_record = D('OrderRecord')->relation(true)->where( array('order_id'=>I('get.id')) )->select();

        $app = date("Y-m-d H:i:s",($order['deliver_time']));
        $this->assign('orderRecord', $order_record);
        $this->assign('num', count($orderGood));
        $this->assign('sum', $sum);
        $this->assign('endSum', $endSum);
        $this->assign('orderGoods', $orderGood);
        $this->assign('order', $order);
        $this->assign('pay_type', $pay_type);
        $this->assign('orderThrough', $orderThrough);
        $this->assign('num', count($orderThrough));
        $this->display();
    }

    // 修改订单支付状态
    public function set_status()
    {
        $do_type = I('post.do_type');
        $field_arr = array("pay" ,"unpay"); // 付款  取消付款
        if(!in_array($do_type ,$field_arr)){
            $this->ajaxReturn(array("status" => "error" ,"msg" => "操作失败"));
        }
        $order = M('order')->where( array('id' => I('post.id')) )->find();
        if(!$order){
            $this->ajaxReturn(array("status" => "error" ,"msg" => "订单有误"));
        }
        // 修改订单状态
        $save_data["is_pay"] = $do_type == "pay" ? 1 : -1;
        M('order')->where( array('id' => I('post.id')) )->save($save_data);
        $type = $do_type == "pay" ? "付款" : "取消付款";
        $msg = GetManagerNameById(session("manager_id")). " 操作订单：". $order['order_id'] ."[{$type}]";
        order_opt_log($msg ,$order['order_id']);
        $this->ajaxReturn(array("status" => "success"));
    }

    //删除已经取消的订单
    public function del() {
        $map['id'] = I('post.id');
        $status = M('order')->where($map)->getField('status');
        if ($status == -1) {
            M('order')->where($map)->delete();
            M('orderGood')->where( array('order_id'=>I('post.id')) )->delete();
            M('orderThrough')->where( array('order_id'=>I('post.id')) )->delete();
        }
        $this->ajaxReturn(1);
    }

    //编辑订单
    public function edit() {
        if (IS_POST) {
            $consignee = trim(I('post.consignee'));
            $phone = trim(I('post.phone'));
            $detail_area = trim(I('post.detail_area'));
            if (empty($consignee)) {
                $this->error('请填写收货人!');
            }

            if (!isMobile($phone)) {
                $this->error('请填写正确的手机号码!');
            }

            if (empty($detail_area)) {
                $this->error('请填写正确的详细地址!');
            }

            $data = array(
                'detail_area' => I('post.detail_area'),
                'consignee' => $consignee,
                'phone' => $phone,
                'update_order' => I('post.update_order'),
                'discount' => I('post.discount')
            );
            $order_id = I('post.order_id');
            $discount = I('post.discount');
            $order = M('order')->where( array('id'=>$order_id) )->find();
            if ($discount >= $order['price']) {
                $this->ajaxReturn(-1);
            } else {
                M('order')->where( array('id'=>$order_id) )->save($data);
                $this->success('修改成功！', I('post.prev'));
            }
        } else {

            //订单的基本信息和收货信息
            $map['id'] = I('get.id');
            $order = D('Order')->order('id DESC')->where($map)->find();

            //订单里面的商品
            $orderGood = M('orderGood')->alias('a')->field('a.*, b.g_name,b.price,a.id as iid,b.img')->join('LEFT JOIN __GOOD__ b ON a.good_id=b.id')
                ->where( array('a.order_id'=>I('get.id')) )
                ->select();

            //收货地址
            $address = M("agent_address")->where("address_id = %d" ,array($order['address_id']))->find();
            $this->assign('address', $address);
            $this->assign('orderGoods', $orderGood);
            $this->assign('order', $order);
            $this->assign('address', $address);
            $this->assign('prev', $_SERVER['HTTP_REFERER']);
            $this->display();
        }
    }

    public function msg_conf()
    {
        $upgo = M('model_message')->where(array('model_name'=>"上级推送通知"))->find();
        $recharge = M('model_message')->where(array('model_name'=>"充值消息通知"))->find();
        $this->assign('recharge',$recharge);
        $this->assign('upgo',$upgo);
        $this->display();
    }

    public function edit_config()
    {
        if (IS_POST) {
            $model_name = I("post.model_name");
            $model_id = trim(I("post.model_id"));
            $model_title = trim(I("post.model_title"));
            $content_begin = trim(I("post.content_begin"));
            $content_end = trim(I("post.content_end"));

            if (empty($model_id)) {
                $this->error('请填写模板ID');
            }

            if (empty($model_title)) {
                $this->error('请填写模板标题');
            }

            if (empty($content_begin)) {
                $this->error('请填写内容开头');
            }

            if (empty($content_end)) {
                $this->error('请填写内容结束语');
            }
            $date['model_name'] = $model_name;
            $date['model_id'] = $model_id;
            $date['model_title'] = $model_title;
            $date['content_begin'] = $content_begin;
            $date['content_end'] = $content_end;
            $req = M('model_message')->where(array('model_name' => $model_name))->find();
            if (!empty($req)) {
                $rep = M("model_message")->where(array('model_name' => $model_name))->save($date);
            } else {
                $rep = M("model_message")->add($date);
            }
            if (!empty($rep)) {
                $this->success("保存成功", U("Order/msg_conf"), 1);
            } else {
                $this->error("保存失败",$_SERVER['HTTP_REFERER'],2);
            }
        } else {
            $id = I('get.id');
            $model_name = I('get.model_name');
            $upgo = M('model_message')->where(array('id'=>$id))->find();
            $this->assign('model_name',$model_name);
            $this->assign('upgo',$upgo);
            $this->display();
        }
    }

    public function selectExcel() {

        $data=import_excel('./Uploads/excel/1.csv');
        print_r($data);
    }

    // 订单价格修改
    public function modify_price()
    {
        if(IS_POST){
            $dis_price = to_int(I("post.dis_price"));
            $dis_freight = to_int(I("post.dis_freight"));
            $order_id = to_int(I("post.order_id"));
            $order = M("order")->where("id = %d", array($order_id))->find();
            $price = ($order["price"] - $order['freight_price']);
            if($dis_price >= $price || $dis_freight > $order['freight_price']){
                $this->error("折扣填写不符" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $order_freight = $order['freight_price'] - $dis_freight;
            M("order")->where("id = %d", array($order_id))->save(array(
                "price" => ($price - $dis_price + $order_freight),
                "freight_price" => $order_freight,
            ));
            $msg = GetManagerNameById(session("manager_id")). " 操作订单：". $order['order_id'] ."[金额：- {$dis_price}；运费：- {$dis_freight}]";
            order_opt_log($msg ,$order['order_id']);
            $this->success("操作成功" ,U('Order/detail',array('id'=>$order_id)) ,1);
        }else{
            $order = M("order")->where("id = %d", array(I("get.id")))->find();
            if(!$order){
                $this->error("请求有误");
            }
            $this->assign("order" ,$order);
            $this->display();
        }
    }

    //生成发货单
    public function  invoice(){
        if(IS_POST){
            //发货时间
            $order_time = I('post.order_time');
            //订单号
            $id = I('post.order_id');
            //发货订单号
            $delivery_num = I('post.delivery_num');
            if(!$delivery_num){
                $this->error("发货订单号为空",$_SERVER["HTTP_REFERER"],3);
            }
            //已经发货的商品数量
            $deliveryed_num = I('post.deliveryed_num');
            if(!$deliveryed_num){
                $this->error("商品数量不能为空",$_SERVER["HTTP_REFERER"],3);
            }
            //留言
            $remark = I('post.remark');
            $good_id = I('post.good_id');
            $good_type = I('post.good_type');


            M('order')->where(array('id'=>$id))->setField(array('code_num'=>$delivery_num,'update_order'=>$remark,'deliver_time'=>strtotime($order_time),'is_deliver'=>1));
            //插入实际发货数据
            foreach ($good_id as $key => $val){
                M('order_good')->where(array('order_id'=>$id,'good_id'=>$val,'good_type'=>$good_type[$key]))
                    ->setField('reality_num',$deliveryed_num[$key]);
            }
//             //储存操作记录
            $order_sn = M('order')->where(array('id'=>$id))->getField('order_id');
            $msg = GetManagerNameById(session("manager_id"))." 操作订单：生成".$order_sn."订单的发货单";
            order_opt_log($msg ,$order_sn);
//
            $this->success("保存成功" ,U("Order/index") ,1);
        }else{
            //订单的基本信息和收货信息
            $map['id'] = I('get.id');
            $order = D('Order')->order('id DESC')->relation(true)->where($map)->find();
            //下单人
            $buyer = M('agent')->where(array('agent_id'=>$order['uid']))->find();
            //支付方式
            $p_name = M('payment')->where(array('p_id'=>$order['pay_type']))->getField('p_name');
            //发货物流
            $logistics = M('express')->where(array('id'=>$order['send_type']))->getField('e_name');
            //订单里面的商品
            $orderGood = M('orderGood')->alias('a')->join('LEFT JOIN __GOOD__ ON a.good_id=__GOOD__.id')->where( array('a.order_id'=>I('get.id')) )->select();
            $data = M('order_record')->where(array('uid'=>session('role_id'),'order_id'=>$map['id']))->find();

            if(!$data){
                $consignor['name'] = session('name');
                $consignor['time'] = date("Y-m-d H:i:s");
                $this->assign('consignor',$consignor);
            }else{
                $data['name'] = M('manager')->where(array('id'=>session('role_id')))->getField('name');
                $data['time'] =date("Y-m-d H:i:s",$data['time']);
                $this->assign('consignor',$data);
            }
            $this->assign('orderGoods',$orderGood);
            $this->assign('buyer',$buyer);
            $this->assign('logistics',$logistics);
            $this->assign('data',$data);
            $this->assign('order', $order);
            $this->assign('p_name',$p_name);
            $this->display();
        }
    }

    public function return_list() {
        if(IS_POST){
            $order_status = I("post.order_status");
            $where['shop_id'] = session('shop_id');
            if($order_status){
                $where['order_status'] = $order_status;
            }
            $order_num = I("post.order_num");
            if($order_num){
                $where['order_id'] = M('order')->where(array('order_id'=>$order_num))->getField('id');
            }
            $end_time = strtotime(I("post.end_time"));
            $start_time =strtotime(I("post.start_time"));
            if($end_time||$start_time){
                $count = M('back_order')->where($where)->where("$start_time < time AND $end_time > time")->count();
                $page = set_page($count, C('PAGE_NUM'));
                $show = $page->show();
                $res = M('back_order')->where($where)->where("$start_time < time AND $end_time > time")
                    ->limit($page->firstRow.','.$page->listRows)->select();
            }else{
                $count = M('back_order')->where($where)->count();
                $page = set_page($count, C('PAGE_NUM'));
                $show = $page->show();
                $res = M('back_order')->where($where)
                    ->limit($page->firstRow.','.$page->listRows)->select();
            }
            foreach ($res as $key=>$value){
                $res[$key]['t_order_id'] = M('order')->where(array('id'=>$value['order_id']))->getField('order_id');
                $uid =  M('order')->where(array('id'=>$value['order_id']))->getField('uid');
                $res[$key]['name'] = M('agent')->where(array('agent_id'=>$uid))->getField('agent_name');
                $send_type = M('order')->where(array('id'=>$value['order_id']))->getField('send_type');
                $res[$key]['send_type'] = M('express')->where(array('id'=>$send_type))->getField('e_name');
                $res[$key]['consignee'] = M('order')->where(array('id'=>$value['order_id']))->getField('consignee');
                $res[$key]['user_phone'] = M('order')->where(array('id'=>$value['order_id']))->getField('user_phone');
                $res[$key]['price'] = M('order')->where(array('id'=>$value['order_id']))->getField('price');
                $res[$key]['back_time'] = date("Y-m-d H:i:s",$value['time']);
                $res[$key]['back_status'] = $value['order_status'];
            }
            $data['order_status'] = $order_status;
            $data['order_num'] = $order_num;
            if($start_time||$end_time){
                $data['start_time'] =  date("Y-m-d H:i:s",$start_time);
                $data['end_time'] = date("Y-m-d H:i:s",$end_time);
            }
            $this->assign('data',$data);
            $this->assign('page',$show);
            $this->assign('count',$count);
            $this->assign('order_info',$res);

            $this->display();

        }else{
            $count = M('back_order')->where(array('shop_id'=>session("shop_id")))->count();
            $page = set_page($count, C('PAGE_NUM'));
            $show = $page->show();
            $res = M('back_order')->where(array('shop_id'=>session('shop_id')))->order('time DESC')->limit($page->firstRow.','.$page->listRows)->select();
            foreach ($res as $key=>$value){
                $res[$key]['t_order_id'] = M('order')->where(array('id'=>$value['order_id']))->getField('order_id');
                $uid =  M('order')->where(array('id'=>$value['order_id']))->getField('uid');
                $res[$key]['name'] = M('agent')->where(array('agent_id'=>$uid))->getField('agent_name');
                $send_type = M('order')->where(array('id'=>$value['order_id']))->getField('send_type');
                $res[$key]['send_type'] = M('express')->where(array('id'=>$send_type))->getField('e_name');
                $res[$key]['consignee'] = M('order')->where(array('id'=>$value['order_id']))->getField('consignee');
                $res[$key]['user_phone'] = M('order')->where(array('id'=>$value['order_id']))->getField('user_phone');
                $res[$key]['price'] = M('order')->where(array('id'=>$value['order_id']))->getField('price');
                $res[$key]['back_time'] = date("Y-m-d H:i:s",$value['time']);
                $res[$key]['back_status'] = $value['order_status'];
            }

            $this->assign('page',$show);

            $this->assign('count',$count);
            $this->assign('order_info',$res);
            $this->display();
        }

    }

    public function return_good_info(){

        if(IS_AJAX){
            $judge = trim(I("post.judge"));
            $status = I("post.status");
            if(empty($status)){
                $this->error("状态错误",$_SERVER['HTTP_REFERER'] );
            }
            $back_sum = to_int(I("post.back_sum"));
            $order_id = trim(I("post.order_id"));
            $good_id = trim(I("post.good_id"));
            $order_sn = M("order")->where(array("id"=>$order_id))->getField("order_id");
            M('back_order')->where(array('order_id'=>$order_id,'good_id'=>$good_id))->setField('order_status',$status);
            M('back_order')->where(array('order_id'=>$order_id,'good_id'=>$good_id))->setField('judge_mes',$judge);
            M('back_order')->where(array('order_id'=>$order_id,'good_id'=>$good_id))->setField('judge_time',NOW_TIME);

            //退预存款
            if($status == '2'){
                $agent_id = M('back_order')->where(array('order_id'=>$order_id,'good_id'=>$good_id))->getField('agent_id');
                $money = M('agent')->where(array('agent_id'=>$agent_id))->getField('money');
                $new_money = $money + $back_sum;
                M('agent')->where(array('agent_id'=>$agent_id))->setField('money',$new_money);
                $msg = GetManagerNameById(session("manager_id")). " 操作订单：". $order_sn ."退货申请通过，返余额".$back_sum."元";
            }else{
                $msg = GetManagerNameById(session("manager_id")). " 操作订单：". $order_sn ."退货申请失败";
            }
            order_opt_log($msg ,$order_sn);


            //最好之前有个短信通知
            $this->ajaxReturn(1);
        }else{
            $order_id = I("get.order_id");
            $good_id = I("get.good_id");
            $t_order_id = M('order')->where(array('id'=>$order_id))->getField('order_id');
            $uid = M('order')->where(array('id'=>$order_id))->getField('uid');
            $name = M('agent')->where(array('agent_id'=>$uid))->getField('agent_name');
            $info =  M('back_order')->where(array('order_id'=>$order_id,'good_id'=>$good_id))->find();
            $info['name'] = $name;
            $info['t_order_id'] = $t_order_id;
            $info['time'] = date("Y-m-d H:i:s",$info['time']);
            if(!empty($info['judge_time'])){
                $info['judge_time'] = date("Y-m-d H:i:s",$info['judge_time']);
            }
            $pics = M('back_img')->where(array('order_id'=>$order_id,'good_id'=>$good_id))->select();

            $info['img'] = M('good')->where(array('id'=>$info['good_id']))->getField('img');
            $info['name'] = M('good')->where(array('id'=>$info['good_id']))->getField('g_name');

            $this->assign('pics',$pics);
            $this->assign('info',$info);
            $this->display();
        }
    }

    public function scoket() {
        $this->display();
    }

    //待平台发货订单
    public function ready_send(){
        //当执行查询的时候
        $search = I('get.btn');
        $export =  I('get.export');
        $map['shop_id'] = session('shop_id');
        if ($search || $export) {
            $start = strtotime(trim(I('get.start_time')));
            $end = strtotime(trim(I('get.end_time')));

            //填写下单时间
            if ($start && $end) {
                $map['time'] = array('between', array($start, $end));
            } elseif($start) {
                $map['time'] = array('EGT', $start);
            } elseif($end) {
                $map['time'] = array('ELT', $end);
            }

            //下单用户名或手机号码
            $u_name = trim(I('get.user_name'));
            if ($u_name) {

                $bool = preg_match("/^1[34578]{1}\d{9}$/",$u_name);
                if($bool){
                    $map['phone'] = $u_name;
                }else{
                    $map['consignee'] = array('like','%'.$u_name.'%');
                }
                $this->assign('u_name', $u_name);
            }

            //下单人用户名
            $user_phone = trim(I('get.user_phone'));
            if ($user_phone) {
                $where['agent_name'] = array('like','%'.$user_phone.'%');
                $agent_id = M('agent')->field('agent_id')->where($where)->select();
                $agent_ids ='';
                foreach ($agent_id as $v) {
                    $agent_ids .= $v['agent_id'].',';
                }

                $agent_ids = substr($agent_ids,0,strlen($agent_ids)-1);
                $map['uid'] = array('in', $agent_ids);
                $this->assign('u_phone', $user_phone);
            }


            //订单编号
            $order_id = I('get.order_id');
            if ($order_id) {
                $map['order_id'] = $order_id;
                $this->assign('orderId', $order_id);
            }
        }

        $map['is_platform'] = 1;//待平台发货
        $map['is_deliver'] = -1;
        $map['is_pay'] = 1;
        $map['status'] = array('neq' ,2);

        //查询分页
        $total = D('Order')->relation(true)->where($map)->count();
        $page = set_page($total, C('PAGE_NUM'));

        foreach($map as $key=>$val) {
            $page->parameter[$key] = urlencode($val);
        }
        $show = $page->show();
        $order = D('Order')->order('id DESC')->relation(true)->where($map)->select();



        //当执行导出数据的时候
        if ($export) {

            //把商品信息链接
            foreach ($order as $k=>$v) {
                $order[$k]['goods'] = M('orderGood')
                    ->alias('a')->join('LEFT JOIN __GOOD__ b ON a.good_id=b.id')
                    ->where( array('a.order_id'=>$v['id']) )
                    ->select();
            }

            $order = D('order')->format($order);


            $strTable ='<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;font-weight: bold;">订单编号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;"width="100">下单人</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">收货人</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">收货人号码</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">支付状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">订单状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">发货状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">下单时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">运费</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">收货地址</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">商品名称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">商品数量</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">单价</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">小计</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">订单总价(含运费)</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;font-weight: bold;" width="*">商品货号</td>';
            $strTable .= '</tr>';

            foreach ($order as $key=>$val) {
                $address = $val['province'].$val['city'].$val['area'].$val['detail_address'];
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_id'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['agent_name'].' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['is_pay'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['status'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['is_deliver'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['time'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['freight_price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$address.'</td>';
                $g_names = $good_sns = $num_s = $good_price = $avg = '';
                foreach($order[$key]['goods'] as $goods) {
                    $g_names .= $goods['g_name']."<br />";
                    $good_sns .= $goods['good_sn']."<br />";
                    $num_s .= $goods['num']."<br />";
                    $good_price .= $goods['goods_price']."<br />";
                    $avg .= ($goods['goods_price']/$goods['num'])."<br />";
                }

                $strTable .= '<td style="text-align:left;font-size:12px;">'.$g_names.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$num_s.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$avg.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$good_price.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$good_sns.' </td>';
                $strTable .= '</tr>';
            }
            $strTable .='</table>';
            createExcel($strTable, '微商系统订单');

        } else {
            $order = D('Order')->order('id DESC')->relation(true)->where($map)->limit($page->firstRow.','.$page->listRows)->select();
        }

        $this->assign('start_time',I('get.start_time'));
        $this->assign('end_time',I('get.end_time'));
        $this->assign('page',$show);
        $this->assign('orders', $order);
        $this->display();
    }

    public function  send_order(){
        //当执行查询的时候
        $search = I('get.btn');
        $export =  I('get.export');
        if ($search || $export) {
            $start = strtotime(trim(I('get.start_time')));
            $end = strtotime(trim(I('get.end_time')));


            //订单编号
            $order_id = I('get.order_id');
            if ($order_id) {
                $map['order_id'] = $order_id;
                $this->assign('orderId', $order_id);
            }

            //填写下单时间
            if ($start && $end) {
                $map['time'] = array('between', array($start, $end));
            } elseif ($start) {
                $map['time'] = array('EGT', $start);
            } elseif ($end) {
                $map['time'] = array('ELT', $end);
            }


            //下单用户名或手机号码
            $u_name = trim(I('get.user_name'));
            if ($u_name) {

                $bool = preg_match("/^1[34578]{1}\d{9}$/", $u_name);
                if ($bool) {
                    $map['phone'] = $u_name;
                } else {
                    $map['consignee'] = array('like', '%' . $u_name . '%');
                }
                $this->assign('u_name', $u_name);
            }
        }

        $map['is_deliver'] = '1';
        $map['is_platform'] = '1';
        $map['shop_id'] = session('shop_id');

        //查询分页
        $total = M('order')->where($map)->count();
        $page = set_page($total, C('PAGE_NUM'));
        $show = $page->show();

        $res = M('order')->where(array($map))->limit($page->firstRow.','.$page->listRows)->select();
        foreach ($res as $key=>$value){
            $res[$key]['send_type'] = M('express')->where(array('id'=>$value['send_type']))->getField('e_name');
            $res[$key]['time'] = date("Y-m-d H:i:s",$value['time']);
            $res[$key]['deliver_time'] = date("Y-m-d H:i:s",$value['deliver_time']);
            $res[$key]['pay_type'] = M('payment')->where(array('p_id'=>$value['pay_type']))->getField('p_name');
        }

        $this->assign('start_time', trim(I('get.start_time')));
        $this->assign('end_time', trim(I('get.end_time')));
        $this->assign('orders',$res);
        $this->assign('page',$show);
        $this->display();
    }

    // 订单操作记录
    public function order_opt_records()
    {
        $this->display();
    }

    // ajax订单操作记录
    public function ajax_logs_list()
    {
        $shop_id = session("shop_id");
        $where = " 1 = 1 AND shop_id = $shop_id"; // 搜索条件
        (I('order_sn') !== '') && $where = "$where AND order_id = ".I('order_sn') ;
        $count = M('order_record')->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $logsList = M('order_record')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('logs',$logsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

}